package com.example.taobaou.ui.Custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.taobaou.R;
import com.example.taobaou.utils.LogUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TextFlowLayout extends ViewGroup {

    private List<String> mTextList = new ArrayList<>();
    public static final float DEFAULT_SPACE = 10;
    private float mItemHorizontaSpace = DEFAULT_SPACE;
    private float mItemVerticalSpace = DEFAULT_SPACE;
    private int mSelfWidth;
    private int itmeHeight;
    private OnFlowTextItemClickListener mItemClickListener = null;

    public float getmItemHorizontaSpace() {
        return mItemHorizontaSpace;
    }

    public void setmItemHorizontaSpace(float mItemHorizontaSpace) {
        this.mItemHorizontaSpace = mItemHorizontaSpace;
    }

    public float getmItemVerticalSpace() {
        return mItemVerticalSpace;
    }

    public void setmItemVerticalSpace(float mItemVerticalSpace) {
        this.mItemVerticalSpace = mItemVerticalSpace;
    }

    public TextFlowLayout(Context context) {
        this(context, null);
    }

    public TextFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FlowTextStyle);
        mItemHorizontaSpace = ta.getDimension(R.styleable.FlowTextStyle_horizontalSpace, DEFAULT_SPACE);
        mItemVerticalSpace = ta.getDimension(R.styleable.FlowTextStyle_verticalSpace, DEFAULT_SPACE);
        ta.recycle();
        LogUtils.d(this, "mItemHorizontalSpace == > " + mItemHorizontaSpace);
        LogUtils.d(this, "mItemVerticalSpace == > " + mItemVerticalSpace);
    }

    public List<String> getmTextList() {
        return mTextList;
    }

    public void setTextList(List<String> textList) {
        removeAllViews();
        mTextList.clear();
        this.mTextList.addAll(textList);
        Collections.reverse(mTextList);//翻转集合
        //遍历内容
        for (String text : mTextList) {
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view, this, false);
            item.setText(text);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mItemClickListener != null) {
                        mItemClickListener.onFlowTextItemClick(text);
                    }
                }
            });

            addView(item);
        }
    }


    private List<List<View>> lines = new ArrayList<>();//描述多行

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() == 0) {
            return;
        }
        List<View> line = null;//描述单行
        lines.clear();
        mSelfWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        //测量
        //测量子view
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View itemView = getChildAt(i);
            measureChild(itemView, widthMeasureSpec, heightMeasureSpec);
            if (line == null) {
                //说明当前行为空，可以添加进来
                line = createNewLine(itemView);
            } else {
                //判断是否可以继续添加
                if (canBeAdd(itemView, line)) {
                    //可以添加
                    line.add(itemView);
                } else {
                    //不能添加，新创建一行
                    line = createNewLine(itemView);
                }
            }

        }
        itmeHeight = getChildAt(0).getMeasuredHeight();
        //测量自己
        int sselfHight = (int) (lines.size() * itmeHeight + mItemVerticalSpace * (lines.size() + 1) + 0.5f);
        //父view的宽度是获取的屏幕宽度然后减去左右边距，高度是（行数*子view的高度    +      上下间距*（行数+1）     最后为了防止四舍五入导致过小再+0.5）
        setMeasuredDimension(mSelfWidth, sselfHight);
    }

    private List<View> createNewLine(View itemView) {
        List<View> line = new ArrayList<>();
        line.add(itemView);
        lines.add(line);
        return line;
    }

    /**
     * 判断当前宽度是否可以继续添加view
     *
     * @param itemView
     * @param line
     */
    private boolean canBeAdd(View itemView, List<View> line) {
        //所有已经添加的子view的宽度加上边距，再加上新添加的view和边距
        //如果结果小于父控件的宽度就可以继续添加，如果超过了则不能继续添加
        int totalWidth = itemView.getMeasuredWidth();
        for (View view : line) {
            totalWidth += view.getMeasuredWidth();
        }
        totalWidth += mItemHorizontaSpace * (line.size() + 1);
        return totalWidth <= mSelfWidth;
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        //摆放
        int topOffSet = (int) mItemHorizontaSpace;
        for (List<View> views : lines) {
            //views是每一行
            int leftOffSet = (int) mItemHorizontaSpace;
            for (View view : views) {
                //每一行里的每一个item
                view.layout(leftOffSet, topOffSet, leftOffSet + view.getMeasuredWidth(), topOffSet + view.getMeasuredHeight());
                //每摆放一个下一个摆放的起始位置都要加上前一个的宽度再加一上间隔
                leftOffSet += view.getMeasuredWidth() + mItemHorizontaSpace;
            }
            //每摆放完一行下一行起始位置回到最初起始高度都要加上上一行的高度再加上上下的间隔
            topOffSet += itmeHeight + mItemHorizontaSpace;

        }
    }

    public void setOnFlowTextItemClickListener(OnFlowTextItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    public interface OnFlowTextItemClickListener {
        void onFlowTextItemClick(String text);
    }
}

